﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FySystem.Logs
{
    /// <summary>
    /// 第二版日志，对通用性做一些优化
    /// 这个类是日志上下文，不包含写日志的具体实现，具体实现通过ILog来做，这样就可以对日志进行扩展
    /// </summary>
    public class FyLogContextV2
    {
        private static LogFlow _logFlow = null;

        /// <summary>
        /// 初始化日志
        /// </summary>
        /// <param name="ilog"></param>
        public static void InitLog(ILog ilog)
        {
            _logFlow = new LogFlow(ilog);
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="title"></param>
        /// <param name="log"></param>
        public static void WriteLog(string title, string log)
        {
            GenLogItem(title, log);
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log)
        {
            GenLogItem(log);
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="title"></param>
        /// <param name="error"></param>
        public static void WriteError(string title, string error)
        {
            GenLogItem(title, error, true);
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="error"></param>
        public static void WriteError(string error)
        {
            GenLogItem(error, true);
        }

        private static void GenLogItem(string title, string log, bool iserr = false)
        {
            try
            {
                LogItem logItem = new LogItem();
                if (string.IsNullOrEmpty(title))
                    logItem.Title = "";
                else
                    logItem.Title = title;
                logItem.Log = log;
                logItem.IsErr = iserr;
                _logFlow.Enqueue(logItem);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void GenLogItem(string log, bool iserr = false)
        {
            try
            {
                LogItem logItem = new LogItem();
                logItem.Title = "";
                logItem.Log = log;
                logItem.IsErr = iserr;
                _logFlow.Enqueue(logItem);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
